//
//  WHRegisterView.m
//  SquirrelCourier
//
//  Created by 邓伟浩 on 2019/1/4.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHRegisterView.h"
#import "WHMessageInputCell.h"
#import "WHCodeInputCell.h"

@interface WHRegisterView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *messageTableView;

@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) NSArray *placeHolderArray;
@property (nonatomic, strong) NSMutableArray *messageArray;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) NSURLSessionDataTask *dataTask;

@end

@implementation WHRegisterView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initParams];
        [self setUpUI];
    }
    return self;
}

- (void)initParams {
    _messageArray = @[@"", @"", @"", @""].mutableCopy;
    _imageArray = @[@"login_phoneNumber_icon", @"login_code_icon", @"login_password_icon", @"login_password_icon"];
    _placeHolderArray = @[@"输入手机号", @"输入验证码", @"输入6-12位数字或字母", @"再次输入6-12位数字或字母"];
}

- (void)setUpUI {
    UITableView *messageTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self addSubview:messageTableView];
    
    messageTableView.delegate = self;
    messageTableView.dataSource = self;
    messageTableView.tableFooterView = [self tableFooterView];
    messageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    messageTableView.backgroundColor = KClearColor;
    [messageTableView registerClass:[WHMessageInputCell class] forCellReuseIdentifier:NSStringFromClass([WHMessageInputCell class])];
    [messageTableView registerClass:[WHCodeInputCell class] forCellReuseIdentifier:NSStringFromClass([WHCodeInputCell class])];
    
    [messageTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
    _messageTableView = messageTableView;
}

- (UIView *)tableFooterView {
    UIView *tableFooterView = [[UIView alloc] init];
    tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(176));
    
    CGFloat leftGap = kRealwidth(32);
    UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:okButton];
    NSString *okTitle = @"完成";
    NSAttributedString *okAttributeStr = [[NSAttributedString alloc] initWithString:okTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [okButton setAttributedTitle:okAttributeStr forState:UIControlStateNormal];
    [okButton setBackgroundImage:[UIImage imageWithColor:CMDarkOrangeColor] forState:UIControlStateNormal];
    okButton.frame = CGRectMake(leftGap, kRealwidth(34), KScreenWidth-2*leftGap, kRealwidth(45));
    ViewRadius(okButton, kRealwidth(45)/2);
    
    UIButton *acceptRuleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:acceptRuleButton];
    acceptRuleButton.frame = CGRectMake(leftGap, okButton.bottom+kRealwidth(30), KScreenWidth-2*leftGap, kRealwidth(14));
    NSString *acceptText = @"注册即同意";
    NSMutableAttributedString *acceptAttrStr = [[NSMutableAttributedString alloc] initWithString:acceptText attributes:@{NSForegroundColorAttributeName:CFontContentLightGrayColor, NSFontAttributeName:SYSTEMFONT(kRealwidth(14))}];
    NSString *serviceText = @"《松鼠侠协议》";
    NSMutableAttributedString *serviceAttrStr = [[NSMutableAttributedString alloc] initWithString:serviceText attributes:@{NSForegroundColorAttributeName:CMDarkOrangeColor, NSFontAttributeName:SYSTEMFONT(kRealwidth(14))}];
    [acceptAttrStr appendAttributedString:serviceAttrStr];
    [acceptRuleButton setAttributedTitle:acceptAttrStr forState:UIControlStateNormal];
    
    [acceptRuleButton addTarget:self action:@selector(acceptRule:) forControlEvents:UIControlEventTouchUpInside];
    [okButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFooterView;
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource ——————

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    
    kWeakSelf(self);
    if (indexPath.row == 1) {
        WHCodeInputCell *codeInputCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHCodeInputCell class]) forIndexPath:indexPath];
        codeInputCell.tipsImageView.image = IMAGE_NAMED(_imageArray[indexPath.row]);
        [codeInputCell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
        codeInputCell.validType = ValideTypeCode;
        
        kWeakSelf(codeInputCell);
        codeInputCell.rightBtnClicked = ^{
            [weakself rightClickedAt:weakcodeInputCell];
        };
        codeInputCell.textChangeBlock = ^(NSString *text) {
            [weakself.messageArray replaceObjectAtIndex:indexPath.row withObject:text];
        };
        codeInputCell.inputTextField.text = [_messageArray objectAtIndex:indexPath.row];
        
        cell = codeInputCell;
    } else {
        WHMessageInputCell *messageInputCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHMessageInputCell class]) forIndexPath:indexPath];
        messageInputCell.tipsImageView.image = IMAGE_NAMED(_imageArray[indexPath.row]);
        [messageInputCell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
        
        messageInputCell.textChangeBlock = ^(NSString *text) {
            [weakself.messageArray replaceObjectAtIndex:indexPath.row withObject:text];
        };
        messageInputCell.inputTextField.text = [_messageArray objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            messageInputCell.validType = ValideTypePhoneNumber;
            messageInputCell.inputTextField.keyboardType = UIKeyboardTypeDefault;
        } else {
            messageInputCell.validType = ValideTypePassword;
            messageInputCell.inputTextField.keyboardType = UIKeyboardTypeASCIICapable;
        }
        
        cell = messageInputCell;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(70);
}

#pragma mark - —————— 事件 ——————
- (void)rightClickedAt:(WHCodeInputCell *)cell {
    NSString *phoneNumber = _messageArray[0];
    if ([phoneNumber isEqualToString:@""]) {
        [WHView showMessage:@"请输入手机号" inView:nil];
        return;
    }
    BOOL is = [WHValidationHelper validateMobile:phoneNumber];
    if (!is) {
        [WHView showMessage:@"请输入正确的手机号" inView:nil];
        return;
    }
    
    [self getCodeWithPhoneNumber:phoneNumber completion:^(id responseObject) {
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                [WHView showMessage:@"获取验证码成功" inView:nil];
                [self startCountDown:cell];
            } else {
                [WHView showMessage:errorMsg inView:nil];
            }
        }
    }];
}

- (void)startCountDown:(WHCodeInputCell *)cell {
    __block int number = 60;
    cell.rightTipsButton.enabled = NO;
    __block NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f block:^(NSTimer * _Nonnull timer) {
        [cell.rightTipsButton setTitleColor:CFontContentLightGrayColor forState:UIControlStateNormal];
        [cell.rightTipsButton setTitle:[NSString stringWithFormat:@"%d秒", number] forState:UIControlStateNormal];
        number = number - 1;
        if (number == 0) {
            [cell.rightTipsButton setTitleColor:CMDarkOrangeColor forState:UIControlStateNormal];
            [cell.rightTipsButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            cell.rightTipsButton.enabled = YES;
            [timer invalidate];
            timer = nil;
        }
    } repeats:YES];
    _timer = timer;
}

- (void)submit:(UIButton *)button {
    if (self.doRegist) {
        self.doRegist(self.messageArray);
    }
}

- (void)acceptRule:(id)sender {
    //    DLog(@"acceptRule");
    if (self.acceptRule) {
        self.acceptRule();
    }
}

- (void)dealloc {
    DLog(@"=== WHForgetPasswordView dealloc ===");
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

#pragma mark —————— 接口 ——————
/** 注册获取验证码 */
- (void)getCodeWithPhoneNumber:(NSString *)phoneNumber completion:(completionBlock)completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_sendCode);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          phoneNumber, @"userCell",
                          @"1", @"type",
                          @"2", @"systeam",
                          nil];
    _dataTask = [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        completion(responseObject);
    } failure:^(NSError *error) {
        
    }];
}

- (void)cancelRequest {
    if (_dataTask) {
        [_dataTask cancel];
        _dataTask = nil;
    }
}

@end
